//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package triger_dao

import (
	"context"

	"atomgit.com/openlinksaas-org/api-server/dao/db_ns"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

type MsgContentDbItem struct {
	RecordId string `bson:"_id"`
	TrigerId string `bson:"trigerId"`
	Content  string `bson:"content"`
}

type _MsgContentDao struct {
	mc *mongo.Collection
}

func newMsgContentDao(db *mongo.Database) (*_MsgContentDao, error) {
	mc := db.Collection(db_ns.DB_NS_TRIGER + "msg_content")
	_, err := mc.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys: bson.D{{"trigerId", 1}},
	})
	if err != nil {
		return nil, err
	}
	return &_MsgContentDao{mc: mc}, nil
}

func (db *_MsgContentDao) Insert(ctx context.Context, dbItem *MsgContentDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_MsgContentDao) Get(ctx context.Context, trigerId, msgId string) (*MsgContentDbItem, error) {
	recordId := GenMsgRecordId(trigerId, msgId)
	retItem := &MsgContentDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": recordId}).Decode(retItem)
	return retItem, err
}

func (db *_MsgContentDao) ListById(ctx context.Context, recordIdList []string) ([]*MsgContentDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{"_id": bson.M{"$in": recordIdList}})
	if err != nil {
		return nil, err
	}
	tmpList := []*MsgContentDbItem{}
	err = cursor.All(ctx, &tmpList)
	if err != nil {
		return nil, err
	}
	tmpMap := map[string]*MsgContentDbItem{}
	for _, tmpItem := range tmpList {
		tmpMap[tmpItem.RecordId] = tmpItem
	}
	retList := []*MsgContentDbItem{}
	for _, recordId := range recordIdList {
		item, ok := tmpMap[recordId]
		if ok {
			retList = append(retList, item)
		}
	}
	return retList, nil
}

func (db *_MsgContentDao) RemoveByTriger(ctx context.Context, trigerId string) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{"trigerId": trigerId})
	return err
}
